<script setup lang="ts">
import { PropType, reactive, ref } from 'vue'
import { ElButton } from 'element-plus'

import { Descriptions } from '@/components/Descriptions'
import { ContentWrap } from '@/components/ContentWrap'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { UploadMultiple } from '@/components/UploadMultiple'

import { useTable } from '@/hooks/web/useTableTest'
import { useIcon } from '@/hooks/web/useIcon'

// 搜索
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import {
  sysRelFileListApi,
  zcAssetWeightLogListApi,
  zcVaccineSingleDetailedListApi,
  zcAssetGpsLogListApi,
  spEnclosureSingleDetailedListApi,
  zcLoanOrderSingleDetailedListApi,
  zcInsuranceOrderSingleDetailedListApi,
  zcAssetMedicalOrderListApi,
  zcAssetFeedLogSingleDetailedListApi
} from '@/api/cy/Assets'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})

console.log(props, 'props')

/****************************** 变量 start ******************************/
const iconFile = useIcon({ icon: 'ic:outline-file-present' })
const sign_eye = useIcon({ icon: 'ep:view' })
const actionType = ref('')
const dialogVisible = ref(false)
// 体征弹窗
const dialogTitle = ref('')
const d_row = ref<any>({})
const dFile = ref([])
// GPS弹窗
const dialogGPS = ref(false)

// 疫苗注射明细列表结构
const columns_vaccine = reactive<TableColumn[]>([
  {
    field: 'code',
    label: '疫苗记录单号',
    width: 150
  },
  {
    field: 'inject_date',
    label: '疫苗注射日期',
    width: 180
  },
  {
    field: 'state',
    label: '状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('vaccine_inject_order_detailed_state', cellValue)
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 180
  }
  // {
  //   field: 'action',
  //   width: 60,
  //   fixed: 'right',
  //   label: '操作'
  // }
])

const {
  register: register_vaccine,
  tableObject: tableObject_vaccine,
  methods: methods_vaccine
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcVaccineSingleDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList: getList_vaccine } = methods_vaccine

// 就医记录明细列表结构
const columns_medical = reactive<TableColumn[]>([
  {
    field: 'code',
    label: '就医记录单号',
    width: 150
  },
  {
    field: 'medical_date',
    label: '就诊日期',
    width: 180
  },
  {
    field: 'symptom',
    label: '症状',
    width: 150
  },
  {
    field: 'state',
    label: '状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('medical_order_detailed_state', cellValue)
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150
  }
  // {
  //   field: 'action',
  //   width: 60,
  //   fixed: 'right',
  //   label: '操作'
  // }
])

const {
  register: register_medical,
  tableObject: tableObject_medical,
  methods: methods_medical
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcAssetMedicalOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList: getList_medical } = methods_medical

// 体征 重量
const columns_sign = reactive<TableColumn[]>([
  {
    field: 'asset_code',
    label: '资产编码',
    width: 150
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 150
  },
  {
    field: 'weight',
    label: '重量',
    width: 100
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 180
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 180
  }
])

const {
  register: register_sign,
  tableObject: tableObject_sign,
  methods: methods_sign
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcAssetWeightLogListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList: getList_sign } = methods_sign

// **********************体征记录******************************************************************

// ***********************图片记录******************************************************************
const url = ref<any>([])

// ******************88***GPS记录明细列表结构*****************************8
// GPS 最新记录
const GpsData = reactive<any>([
  {
    date: 'GPS',
    tableData1: {}
  }
])
// GPS以往记录
let old_GPS = ref<any>([])

function Gpstan(index) {
  switch (index) {
    case 0:
      dialogGPS.value = true
      break
    default:
      console.log('未知类型')
  }
}

// ******************88***栏位记录明细列表结构*****************************8
const columns_fence = reactive<TableColumn[]>([
  {
    field: 'asset_code',
    label: '资产编码',
    width: 150
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 150
  },
  {
    field: 'in_enclosure_name',
    label: '入栏',
    width: 150
  },
  {
    field: 'out_enclosure_name',
    label: '出栏',
    width: 180
  },
  {
    field: 'date',
    label: '出入栏时间',
    width: 180
  }
])

const {
  register: register_fence,
  tableObject: tableObject_fence,
  methods: methods_fence
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spEnclosureSingleDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList: getList_fence } = methods_fence

// *****************************喂养记录明细列表结构 *************************************************************
const columns_feed = reactive<CrudSchema[]>([
  {
    field: 'code',
    label: '喂养记录单号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'feed_time',
    label: '喂养日期',
    width: 200
  },
  {
    field: 'name',
    label: '饲料名称',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'weight',
    label: '喂养重量',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'threshold',
    label: '喂养阈值',
    width: 150
  },
  {
    field: 'note',
    label: '备注',
    width: 200
  }
])

const { allSchemas } = useCrudSchemas(columns_feed)

const {
  register: register_feed,
  tableObject: tableObject_feed,
  methods: methods_feed
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcAssetFeedLogSingleDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList: getList_feed } = methods_feed
// console.log(tableObject_feed.tableList)

// 投保(保险)
const columns_insure = reactive<TableColumn[]>([
  {
    field: 'code',
    label: '保险申报单编码',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'insurance_no',
    label: '保险单号',
    width: 180
  },
  {
    field: 'insurance_data',
    label: '保险日期',
    width: 180,
    search: {
      show: true
    }
  },
  {
    field: 'state',
    label: '保险状态',
    width: 180,
    search: {
      show: true
    }
  },
  {
    field: 'insurance_type',
    label: '保险类型',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('insurance_type', cellValue)
    }
  },
  {
    field: 'rate',
    label: '费率%',
    width: 150
  },
  {
    field: 'unitAmount',
    label: '单位保额（元）',
    width: 150
  },
  {
    field: 'years',
    label: '投保年限',
    width: 150
  },
  {
    field: 'note',
    label: '备注',
    width: 180
  }
  // {
  //   field: 'action',
  //   width: 60,
  //   fixed: 'right',
  //   label: '操作'
  // }
])

const {
  register: register_insure,
  tableObject: tableObject_insure,
  methods: methods_insure
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcInsuranceOrderSingleDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList: getList_insure } = methods_insure

// 贷款
const columns_loanapply = reactive<TableColumn[]>([
  {
    field: 'code',
    label: '贷款申报单编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'loan_no',
    label: '贷款单号',
    width: 180
  },
  {
    field: 'loan_data',
    label: '贷款时间',
    width: 180,
    search: {
      show: true
    }
  },
  {
    field: 'loan_state',
    label: '贷款状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('loan_order_state', cellValue)
    }
  },
  {
    field: 'loan_year',
    label: '贷款年限',
    width: 120
  },
  {
    field: 'note',
    label: '备注',
    width: 150
  }
])

const {
  register: register_loanapply,
  tableObject: tableObject_loanapply,
  methods: methods_loanapply
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcLoanOrderSingleDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList: getList_loanapply } = methods_loanapply
/****************************** 变量 end ******************************/

/****************************** 函数方法 start ******************************/
const action = async (type: string, row) => {
  // console.log(row.state)
  actionType.value = type
  switch (type) {
    case 'file_d':
      dialogTitle.value = '附件'
      d_row.value = row
      if (row.file) {
        dFile.value = JSON.parse(row.file)
      } else {
        dFile.value = []
      }
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 函数方法 end ******************************/

/****************************** 初始化 start ******************************/
const init = async () => {
  // 固定查询条件
  tableObject_vaccine.fixedSearch = {
    asset_id: props.currentRow.id
  }
  // 获取疫苗注射记录明细
  await getList_vaccine()
  // 固定查询条件
  tableObject_medical.fixedSearch = {
    asset_id: props.currentRow.id
  }
  // 获取就医记录明细
  await getList_medical()
  // 固定查询条件

  // // 体征查询条件
  tableObject_sign.fixedSearch = {
    asset_id: props.currentRow.id
  }
  // 获取体征记录明细
  await getList_sign()

  // 照片
  const res = await sysRelFileListApi({
    source: 'asset',
    source_id: props.id,
    pageNo: 1,
    pageSize: 10
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log(res, '照片')
    await res.data
    for (let index = 0; index < res.data.length; index++) {
      url.value.push(res.data[index].file_url)
    }
    await url.value
  }

  // GPS
  const GPS = await zcAssetGpsLogListApi({
    asset_id: props.id,
    pageNo: 1,
    pageSize: 1000
  })
    .catch(() => {})
    .finally(() => {})
  if (GPS) {
    await GPS.data
    GpsData[0].tableData1 = GPS.data[0]
    old_GPS.value = GPS.data
    console.log(GPS.data, 'GPS')
  }

  // 固定查询条件
  tableObject_fence.fixedSearch = {
    vaccine_inject_order_id: props.currentRow.id
  }
  // 栏位记录明细
  await getList_fence()

  // 固定查询条件
  tableObject_feed.fixedSearch = {
    id: props.currentRow.id
  }
  // 喂养记录明细
  await getList_feed()

  // 投保记录
  tableObject_insure.fixedSearch = {
    id: props.currentRow.id
  }
  await getList_insure()

  // 贷款记录
  tableObject_loanapply.fixedSearch = {
    id: props.currentRow.id
  }
  await getList_loanapply()
}
init()
/****************************** 初始化 end ******************************/
</script>

<template>
  <div>
    <ContentWrap title="资产数据">
      <Descriptions :schema="props.detailSchema" :data="props.currentRow">
        <template #breed="{ row }: { row: any }">
          <div>{{ getDictLabel('breed', row.breed) }}</div>
        </template>
        <template #breed_sub="{ row }: { row: any }">
          <div>{{ getDictLabel('breed_sub', row.breed_sub) }}</div>
        </template>
        <template #sex="{ row }: { row: any }">
          <div>{{ getDictLabel('animal_sex', row.sex) }}</div>
        </template>
        <template #purpose="{ row }: { row: any }">
          <div>{{ getDictLabel('purpose', row.purpose) }}</div>
        </template>
        <template #is_die="{ row }: { row: any }">
          <div>{{ getDictLabel('is', row.is_die) }}</div>
        </template>
      </Descriptions>
    </ContentWrap>
    <ContentWrap title="健康档案-疫苗注射记录单">
      <Table
        v-model:pageSize="tableObject_vaccine.pageSize"
        v-model:currentPage="tableObject_vaccine.currentPage"
        :columns="columns_vaccine"
        :data="tableObject_vaccine.tableList"
        :loading="tableObject_vaccine.loading"
        :border="true"
        :pagination="{
          total: tableObject_vaccine.count
        }"
        @register="register_vaccine"
        :selection="false"
      >
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('vaccine_inject_order_detailed_state', row.state) }}</div>
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
        </template>
      </Table>
    </ContentWrap>

    <ContentWrap title="健康档案-就医记录单">
      <Table
        v-model:pageSize="tableObject_medical.pageSize"
        v-model:currentPage="tableObject_medical.currentPage"
        :columns="columns_medical"
        :data="tableObject_medical.tableList"
        :loading="tableObject_medical.loading"
        :border="true"
        :pagination="{
          total: tableObject_medical.count
        }"
        @register="register_medical"
        :selection="false"
      >
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('medical_order_detailed_state', row.state) }}</div>
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
        </template>
      </Table>
    </ContentWrap>

    <ContentWrap title="健康档案-体征单">
      <Table
        v-model:pageSize="tableObject_sign.pageSize"
        v-model:currentPage="tableObject_sign.currentPage"
        :columns="columns_sign"
        :data="tableObject_sign.tableList"
        :loading="tableObject_sign.loading"
        :border="true"
        :pagination="{
          total: tableObject_sign.count
        }"
        @register="register_sign"
        :selection="false"
      >
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('medical_order_detailed_state', row.state) }}</div>
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
        </template>
      </Table>
    </ContentWrap>

    <ContentWrap title="健康档案-照片单">
      <div class="demo-image__preview">
        <el-image
          v-for="(data, index) in url"
          :key="index"
          style="width: 100px; height: 100px"
          :src="data"
          :preview-src-list="url"
          :zoom-rate="1.2"
          :initial-index="index"
          fit="cover"
        />
      </div>
    </ContentWrap>

    <ContentWrap title="健康档案-GPS">
      <el-table border :data="GpsData" style="width: 100%" max-height="500">
        <el-table-column fixed prop="date" width="100" />
        <el-table-column prop="tableData1.asset_code" label="资产编码" width="180" />
        <el-table-column prop="tableData1.earcon_code" label="耳标编号" width="180" />
        <el-table-column prop="tableData1.gps_x" label="gps_x" width="120" />
        <el-table-column prop="tableData1.gps_y" label="gps_y" width="120" />
        <el-table-column prop="tableData1.create_time" label="创建时间" width="180" />
        <el-table-column prop="tableData1.create_user_name" label="创建人" width="120" />
        <el-table-column fixed="right" align="center" label="以往记录" width="100">
          <template #default="scope">
            <!-- <el-button link type="primary" size="small" @click.prevent="hhh(scope.$index)">
              Remove
            </el-button> -->
            <ElButton
              circle
              :icon="sign_eye"
              @click.prevent="Gpstan(scope.$index)"
              title="查看以往记录"
            />
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>

    <ContentWrap title="健康档案-栏位记录单">
      <Table
        v-model:pageSize="tableObject_fence.pageSize"
        v-model:currentPage="tableObject_fence.currentPage"
        :columns="columns_fence"
        :data="tableObject_fence.tableList"
        :loading="tableObject_fence.loading"
        :border="true"
        :pagination="{
          total: tableObject_fence.count
        }"
        @register="register_fence"
        :selection="false"
      >
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('vaccine_inject_order_detailed_state', row.state) }}</div>
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
        </template>
      </Table>
    </ContentWrap>

    <ContentWrap title="健康档案-喂养记录单">
      <Table
        v-model:pageSize="tableObject_feed.pageSize"
        v-model:currentPage="tableObject_feed.currentPage"
        :columns="allSchemas.tableColumns"
        :data="tableObject_feed.tableList"
        :loading="tableObject_feed.loading"
        :border="true"
        :pagination="{
          total: tableObject_feed.count
        }"
        @register="register_feed"
        :selection="false"
      >
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('medical_order_detailed_state', row.state) }}</div>
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
        </template>
      </Table>
    </ContentWrap>

    <ContentWrap title="健康档案-投保记录">
      <Table
        v-model:pageSize="tableObject_insure.pageSize"
        v-model:currentPage="tableObject_insure.currentPage"
        :columns="columns_insure"
        :data="tableObject_insure.tableList"
        :loading="tableObject_insure.loading"
        :border="true"
        :pagination="{
          total: tableObject_insure.count
        }"
        @register="register_insure"
        :selection="false"
      >
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('insurance_order_state', row.state) }}</div>
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
        </template>
      </Table>
    </ContentWrap>

    <ContentWrap title="健康档案-贷款记录">
      <Table
        v-model:pageSize="tableObject_loanapply.pageSize"
        v-model:currentPage="tableObject_loanapply.currentPage"
        :columns="columns_loanapply"
        :data="tableObject_loanapply.tableList"
        :loading="tableObject_loanapply.loading"
        :border="true"
        :pagination="{
          total: tableObject_loanapply.count
        }"
        @register="register_loanapply"
        :selection="false"
      >
        <template #loan_state="{ row }: { row: any }">
          <div>{{ getDictLabel('loan_order_state', row.loan_state) }}</div>
        </template>

        <template #action="{ row }">
          <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" />
        </template>
      </Table>
    </ContentWrap>

    <!-- GPS弹窗 -->
    <Dialog v-model="dialogGPS" title="GPS">
      <!-- 数据值 -->
      <el-table :data="old_GPS" border style="width: 100%">
        <el-table-column prop="asset_code" label="资产编码" width="180" />
        <el-table-column prop="earcon_code" label="耳标编号" width="180" />
        <el-table-column prop="gps_x" label="gps_x" width="120" />
        <el-table-column prop="gps_y" label="gps_y" width="120" />
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column prop="create_user_name" label="创建人" width="120" />
      </el-table>
      <template #footer>
        <ElButton @click="dialogGPS = false">关闭</ElButton>
      </template>
    </Dialog>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <div>
        <UploadMultiple
          ref="dFileRef"
          v-model="dFile"
          :response="{
            url: 'file_url',
            name: 'file_name',
            file_type: 'file_type'
          }"
          disabled
        />
      </div>

      <template #footer>
        <ElButton @click="dialogVisible = false">关闭</ElButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
